package org.saxion.saktiehuis;

import java.util.Map;

import org.saxion.saktiehuis.model.Order;
import org.saxion.saktiehuis.model.Product;
import org.saxion.saktiehuis.model.UserSession;
import org.saxion.saktiehuis.service.OrderItemService;
import org.saxion.saktiehuis.service.OrderService;
import org.saxion.saktiehuis.service.ProductService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class OrderController {

	private static final Logger logger = LoggerFactory
			.getLogger(OrderController.class);

	@Autowired
	ProductService productService;
	@Autowired
	OrderService orderService;
	@Autowired
	OrderItemService orderItemService;
	@Autowired
	UserSession session;

	@RequestMapping(value = "/cart", method = RequestMethod.GET)
	public String shopcart(Model model) {
		model.addAttribute("items", session.getContentOfCart());
		return "cart";
	}

	@RequestMapping(value = "/order", method = RequestMethod.POST)
	public String order(@RequestParam("id") Long id,
			@RequestParam("amount") Integer amount, Model model) {
		Product product = (Product) productService.getProductById(id);
		if (amount != null && amount > 0) {
			session.addProduct(product, amount);
			model.addAttribute("message", "Product in winkelmand geplaatst");
		} else {
			model.addAttribute("message", "Geef een aantal op!");
		}
		model.addAttribute("product", product);
		return "product";
	}

	@RequestMapping(value = "/confirm", method = RequestMethod.GET)
	public String confirm(Model model) {
		Order order = orderService.save(session.getUsername());
		if (order != null) {
			for (Map.Entry<Product, Integer> entry : session.getContentOfCart()
					.entrySet()) {
				orderItemService.save(order, entry.getKey(), entry.getValue());
			}
			session.emptyCart();
		}
		logger.info("Gebruiker " + session.getUsername() + " heeft een bestelling geplaatst");
		return "confirm";
	}
	
	@RequestMapping(value = "/history", method = RequestMethod.GET)
	public String history(Model model) {
		model.addAttribute("items", session.getContentOfCart());
		return "history";
	}

}
